//
//  RHFieldsDataVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/8.
//

#import "RHFieldsDataVC.h"
#import "FieldsCellItemView.h"

@interface RHFieldsDataVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic ,strong) UICollectionView *collectView;

@property (nonatomic ,strong) RHDeviceModel *deviceModel;

@property (nonatomic, strong) RHEndPointModel *endpointModel;
@end

@implementation RHFieldsDataVC
-(instancetype)initWithEndpointModel:(RHEndPointModel*)endpointModel deviceModel:(RHDeviceModel*)deviceModel
{
    if (self = [super init]) {
        _deviceModel = deviceModel;
        _endpointModel = endpointModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getFormData];
}

- (void)setupUI{
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    _collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    [_collectView rounded:8 width:1 color:kBorderColor];
    _collectView.backgroundColor = UIColor.whiteColor;
    [_collectView registerClass:[FieldsCellItemView class] forCellWithReuseIdentifier:@"FieldsCellItemView"];
    _collectView.delegate = self;
    _collectView.dataSource = self;
    _collectView.showsVerticalScrollIndicator = NO;
    _collectView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_collectView];
    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    _collectView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    kWeakSelf;
    [_collectView addHeaderRefresh:^{
        [weakSelf getFormData];
        if (weakSelf.masterEndpointModel) {
            [weakSelf getMasterData];
        }
        if (weakSelf.emsEndpointModel) {
            [weakSelf getEmsData];
        }
    }];
}

-(void)setEmsEndpointModel:(RHEndPointModel *)emsEndpointModel
{
    _emsEndpointModel = emsEndpointModel;
    if (emsEndpointModel) {
        [self getEmsData];
    }
}

- (void)setFormFields:(NSArray *)formFields{
    _formFields = formFields;
    [_collectView reloadData];
//    [_collectView mas_updateConstraints:^(MASConstraintMaker *make) {
//        NSInteger row = formFields.count%3 ? formFields.count/3+1 : formFields.count/3;
//        
//        if(row == 0){
//            make.height.offset(0);
//        }else{
//            //最多只显示6个
//            make.height.offset(row*70 + 20 );
//        }
//    }];
    
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.formFields.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FieldsCellItemView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FieldsCellItemView" forIndexPath:indexPath];
    [cell setModel:self.formFields[indexPath.item] deviceTypeCode:self.deviceModel.deviceTypeCode];
    [cell setIndex:indexPath.row totalCount:self.formFields.count];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWidth = (kUI_WINDOW_W-30)/3.0-0.1;
    DeviceChartFieldModel *model = self.formFields[indexPath.item];
    if ([model.keyCode isEqualToString:@"Inv1_PVEnerSuPri"]) {
        return CGSizeMake(itemWidth * 2, 70);
    }
    return CGSizeMake((kUI_WINDOW_W-30)/3.0-0.1, 70);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 0, 10, 0);
}


- (void)getFormData{
    
    if(self.formFields.count == 0){
        return;
    }
    NSMutableArray *paraKey = [NSMutableArray array];
    NSString *prefixKey = [NSString getEndpointParaPrefixStringWithEndpointCode:self.endpointModel.endpointCode deviceTypeCode:self.deviceModel.deviceTypeCode];
    //这里只获取当前端点的数据点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (prefixKey.length>0) {
            if (obj.keyCode&&[obj.keyCode hasPrefix:prefixKey]) {
                //pcs运行数据中有一些是相乘的参数,如 Pcs_ActivePwrU1/Pcs_DCPowerU1(允许最大充电功率)
                NSString *separateKey;
                if([obj.keyCode containsString:@"*"]){
                    separateKey = @"*";
                }
                if([obj.keyCode containsString:@"/"]){
                    separateKey = @"/";
                }
                if(separateKey){
                    NSArray *keys = [obj.keyCode componentsSeparatedByString:separateKey];
                    if (keys.firstObject && ![paraKey containsObject:keys.firstObject]) {
                        [paraKey addObject:keys.firstObject];
                    }
                    if (keys.lastObject && ![paraKey containsObject:keys.lastObject]) {
                        [paraKey addObject:keys.lastObject];
                    }
                }else{
                   
                    [paraKey addObject:obj.keyCode];
                }
            }
        }else{
            if (obj.keyCode) {
                [paraKey addObject:obj.keyCode];
            }
        }
        
    }];
    if (paraKey.count == 0) {
        return;
    }
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.endpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.endpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
                //对其他样式参数赋值
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                    
                    //对于Pcs_ActivePwrU1/Pcs_DCPowerU1字段的赋值
                    if([obj.keyCode containsString:@"/"]){
                        NSArray *keys = [obj.keyCode componentsSeparatedByString:@"/"];
                        NSString *key1 = [keys firstObject];
                        NSString *key2 = [keys lastObject];
                        if (dic[key1]&&dic[key2]) {
                            double value = [dic[key1] doubleValue] / [dic[key2] doubleValue];
                            if ([dic[keys] doubleValue] == 0) {
                                obj.content = @"0";
                            }else{
                                obj.content = [NSDecimalNumber decimalStringWithDouble:value];
                            }
                            
                        }
                       
                    }
                }];
              
                [self.collectView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
    }];
}

- (void)getEmsData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //pcs的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode.uppercaseString hasPrefix:@"EMS"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                               @"endpointTypeCode":SafeStr(self.emsEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                               @"endpointSn":SafeStr(self.emsEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.collectView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
    }];
}

- (void)getMasterData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //pcs的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"Mtr_"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.masterEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.masterEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.collectView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.collectView endHeaderRefresh];
    }];

}
@end
